import axios, { AxiosRequestConfig } from 'axios'

export default class Axios {
    private instance
    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config)
        this.interceptors()
    }
    // T表示想要的data里的数据类型，D是整个响应结构
    public async request<T, D = ResponseResult<T>>(config: AxiosRequestConfig) {
        return new Promise(async (resolve, reject) => {
            try {
                const response = await this.instance.request<D>(config)
                resolve(response.data)
            } catch (error) {
                reject(error)
            }
        }) as Promise<D>
    }
    private interceptors() {
        this.interceptorsRequest()
        this.interceptorsResponse()
    }
    // 请求拦截器
    private interceptorsRequest() {
        this.instance.interceptors.request.use((config) => {
            return config
        }, (error) => {
            return Promise.reject(error)
        })
    }
    // 响应拦截器
    private interceptorsResponse() {
        this.instance.interceptors.response.use((response) => {
            return response
        }, (error) => {
            return Promise.reject(error)
        })
    }
}